package com.zp.api.aliyun;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.zp.api.aliyun.domain.CreateOutPaintingTaskRequest;
import com.zp.api.aliyun.domain.CreateOutPaintingTaskResponse;
import com.zp.api.aliyun.domain.GetOutPaintingTaskResponse;
import com.zp.enums.ErrorCode;
import com.zp.exception.BusinessException;
import com.zp.utils.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 扩图任务 API 调用
 */
@Slf4j
@Component
public class AliYunOutPaintingTask {
    /**
     * 读取 apiKey
     */
    @Value("${aliYun.apiKey}")
    private String apiKey;

    /**
     * 创建任务请求地址
     */
    public static final String CREATE_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";

    /**
     * 查询结果请求地址
     */
    public static final String GET_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    /**
     * step1: 创建任务获取任务 ID
     *
     * @param request 请求参数
     * @return 任务 ID
     */
    public CreateOutPaintingTaskResponse createTask(CreateOutPaintingTaskRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR, "参数为空");
        // 发送请求(看文档)
        HttpRequest httpRequest = HttpRequest.post(CREATE_OUT_PAINTING_TASK_URL)
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                .header("X-DashScope-Async", "enable")
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .body(JSONUtil.toJsonStr(request));
        try (HttpResponse httpResponse = httpRequest.execute()) {
            if (!httpResponse.isOk()) {
                log.error("请求失败: {}", httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建 AI 扩图任务失败");
            }
            CreateOutPaintingTaskResponse response = JSONUtil.toBean(httpResponse.body(), CreateOutPaintingTaskResponse.class);
            String errorCode = response.getCode();
            if (StrUtil.isNotBlank(errorCode)) {
                // 请求失败
                String errorMessage = response.getMessage();
                log.error("请求失败, errorMessage: {}, errorCode: {}", errorMessage, errorCode);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建任务失败");
            }
            return response;
        }
    }

    /**
     * step2: 根据任务 ID 查询结果
     *
     * @param taskId 任务 ID
     * @return 任务结果
     */
    public GetOutPaintingTaskResponse getOutPaintingByTaskId(String taskId) {
        if (StrUtil.isBlank(taskId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务 id 不能为空");
        }
        try (HttpResponse httpResponse = HttpRequest.get(String.format(GET_OUT_PAINTING_TASK_URL, taskId))
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                .execute()) {
            if (!httpResponse.isOk()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取任务失败");
            }
            return JSONUtil.toBean(httpResponse.body(), GetOutPaintingTaskResponse.class);
        }
    }
}
